import 'package:debug_panel_module/debug_interface.dart';
import 'package:debug_panel_module/proxy/debug_proxy.dart';
import 'package:flutter/material.dart';
import 'package:sensors/sensors.dart';
import 'debughome/pages/debug_panel.dart';

///摇一摇工具类
class ShakeUtil {
  ///单例模式
  ShakeUtil._internal();

  static ShakeUtil _singleton = ShakeUtil._internal();

  factory ShakeUtil() => _singleton;

  bool _isInit = false;

  ///是否已经打开DEBUG面板
  bool _isAlreadyOpen = false;

  ///摇一摇初始化
  ShakeUtil init(BuildContext context) {
    if (_isInit) {
      return _singleton;
    }

    _isInit = true;
    _shakeToOpenDebugPanel(context);

    return _singleton;
  }

  ///摇一摇
  void _shakeToOpenDebugPanel(BuildContext context) {
    assert(() {
      if (!_isInit) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('ShakeUtil is not inited'),
          ErrorDescription(
              'If you are not init ShakeUtil,you cannot get the function of shake'),
        ]);
      }
      return true;
    }());
    accelerometerEvents.listen((AccelerometerEvent event) {
      int value = 35;
      if (event.x >= value ||
          event.x <= -value ||
          event.y >= value ||
          event.y <= -value ||
          event.z >= value ||
          event.z <= -value) {
        print("_isAlreadyOpen=================>$_isAlreadyOpen");
        if (_isAlreadyOpen) {
          return;
        }

        ///只有尚未打开DEBUG面板的时候才能进入DEBUG面板
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => DebugPanelPage(callback: (open) => _isAlreadyOpen = open ,)));

        _isAlreadyOpen = true;
      }
    });
  }

  /// 注入实现类
  void injectDebugImpl(DebugInterface debugImpl) {
     DebugProxy().injectDebugImpl(debugImpl);
  }

}
